﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Context;
using System.Reflection;
using NHibernate.Cfg;

namespace SaladBar.Service.Repositories.NHibernateRepository.SessionManagers
{
    public class SimpleSessionManager : ISessionManager, IDisposable
    {
        private static ISessionFactory _sessionFactory;
        private ISession _currentSession;

        public SimpleSessionManager(Configuration cfg)
        {
            if (_sessionFactory == null)
            {
                cfg.EventListeners.PreUpdateEventListeners = new NHibernate.Event.IPreUpdateEventListener[] { new PersistentObjectEventListener() };
                cfg.EventListeners.PreInsertEventListeners = new NHibernate.Event.IPreInsertEventListener[] { new PersistentObjectEventListener() };

                _sessionFactory = cfg.BuildSessionFactory();
            }
        }

        public ISession GetCurrentSession()
        {
            if (this._currentSession == null)
            {
                this._currentSession = _sessionFactory.OpenSession();
            }
            return this._currentSession;
        }

        public void Dispose()
        {
            if (this._currentSession != null)
            {
                this._currentSession.Close();
                this._currentSession.Dispose();
            }
        }
    }
}
